import { InjectionKey } from 'vue'
import { createStore, Store, useStore as baseUseStore } from 'vuex'

export interface Goods {
  "img-src": string,
  title: string,
  price: number,
  body: string
}

export interface PriceMapValueType {
  count: number,
  unitPrice: number,
  totalPrice: number,
  title: string
}
export interface PriceObject {
  totalPrice: number,
  priceMap: Map<number, PriceMapValueType>
}

export interface State {
  thingsBuy: number[],
  goods: Goods[],
  loginToken: string | null,
  userId: number | null
}
function getCounts(thingsBuy: number[]) {
  const goodsCounts = new Array<number>()
  for (const i of thingsBuy) {
    if (goodsCounts[i - 1] !== undefined) {
      goodsCounts[i - 1]!++
    } else {
      goodsCounts[i - 1] = 1
    }
  }
  return goodsCounts
}
function getGoodsPriceValueObj(goodsCounts: number[], goodsUnitPrices: number[], goodsTitles: string[]) {
  const goodsPriceValueObj = new Map<number, PriceMapValueType>();
  for (let i = 0;i < goodsUnitPrices.length;++i) {
    const goodsCount = goodsCounts[i]
    if (goodsCount === undefined) {
      continue
    }
    const goodsUnitPrice = goodsUnitPrices[i]
    const goodsTotalPrice = goodsCount * goodsUnitPrice
    const goodsTitle = goodsTitles[i]
    goodsPriceValueObj.set(i + 1, {
      count: goodsCount,
      unitPrice: goodsUnitPrice,
      totalPrice: goodsTotalPrice,
      title: goodsTitle
    })
  }
  return goodsPriceValueObj
}
export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
  state() {
    return {
      goods: [],
      thingsBuy: [],
      loginToken: null,
      userId: null
    }
  },
  getters: {
    priceObject(state) : PriceObject {
      const thingsBuy = state.thingsBuy
      const goodsCounts = getCounts(thingsBuy)
      const goodsUnitPrices = state.goods.slice().map(a=>a.price)
      const goodsTitles = state.goods.slice().map(a=>a.title)
      const goodsPriceValueObj = getGoodsPriceValueObj(goodsCounts, goodsUnitPrices, goodsTitles);
      let totalPrice = 0
      goodsPriceValueObj.forEach(value => { totalPrice += value.totalPrice })
      return {
        totalPrice,
        priceMap: goodsPriceValueObj
      }

    }
  },
  mutations: {
    setGoods(state: State, to: Goods[]) {
      state.goods = to
    },
    buyNewThings(state: State, id: number) {
      state.thingsBuy.push(id)
      console.log(state.thingsBuy)
    },
    deleteOldThings(state: State, id: number) {
      state.thingsBuy.splice(state.thingsBuy.indexOf(id), 1)
    },
    setLoginToken(state: State, key: string) {
      state.loginToken = key
    },
    setUserId(state: State, id: number) {
      state.userId = id
    },
    clearThingsBuy(state: State) {
      state.thingsBuy = []
    }
  },
  actions: {

  },
  modules: {

  },
  strict: process.env.NODE_ENV !== 'production'
})
export function useStore() {
  return baseUseStore(key)
}